from flask import Flask, g,render_template
from flask_cors import CORS
from .models import db, init_db
from .api import register_routes

def create_app(config_name='development'):
    """应用工厂函数"""
    app = Flask(
        __name__,
        static_folder='static',
        template_folder='templates'
    )
    
    # 加载配置
    app.config.from_object(f'app.config.{config_name.capitalize()}Config')
    
    # 初始化扩展
    CORS(app, supports_credentials=True)
    db.init(app.config['DATABASE_URI'])
    
    # 注册路由
    register_routes(app)
    
    # 根路由
    @app.route('/')
    def index():
        return render_template('index.html')
        # return app.send_static_file('index.html')
    
    # 注入app到g对象供全局使用
    @app.before_request
    def inject_app():
        g.app = app
    
    # 初始化数据库
    with app.app_context():
        init_db()
    
    return app
